import React, { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Heart, Star, ShoppingCart, BookOpen, Clock, Users, ArrowLeft, ChevronLeft, ChevronRight, Play, Pause } from 'lucide-react';
import { useAppStore, CartItem } from '../stores/appStore';

const BookDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { books, currentUser, toggleFavorite, addToCart } = useAppStore();
  const [currentPage, setCurrentPage] = useState(0);
  const [isPlaying, setIsPlaying] = useState(false);
  const [quantity, setQuantity] = useState(1);

  const book = books.find(b => b.id === id);

  if (!book) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-primary-50 to-accent-50 flex items-center justify-center">
        <div className="text-center">
          <div className="text-6xl mb-4">📚</div>
          <h2 className="text-2xl font-bold text-gray-800 mb-2">绘本未找到</h2>
          <p className="text-gray-600 mb-4">抱歉，您要找的绘本不存在</p>
          <button
            onClick={() => navigate('/books')}
            className="px-6 py-2 bg-primary-500 text-white rounded-full hover:bg-primary-600 transition-colors"
          >
            返回绘本馆
          </button>
        </div>
      </div>
    );
  }

  const isFavorite = currentUser?.favorites.includes(book.id) || false;
  const totalPages = book.previewImages?.length || 1;

  const handlePrevPage = () => {
    setCurrentPage(prev => Math.max(0, prev - 1));
  };

  const handleNextPage = () => {
    setCurrentPage(prev => Math.min(totalPages - 1, prev + 1));
  };

  const handleToggleFavorite = () => {
    if (currentUser) {
      toggleFavorite(book.id);
    } else {
      navigate('/login');
    }
  };

  const handleAddToCart = () => {
    if (!currentUser) {
      navigate('/login');
      return;
    }
    
    const cartItem: CartItem = {
      id: `cart_${Date.now()}`,
      type: 'book',
      itemId: book.id,
      title: book.title,
      price: book.price,
      quantity: quantity,
      image: book.coverImage
    };
    
    addToCart(cartItem);
    alert(`已将 ${quantity} 本《${book.title}》加入购物车`);
  };

  const handleStartReading = () => {
    if (!currentUser) {
      navigate('/login');
      return;
    }
    // Start reading logic here
    navigate(`/read/${book.id}`);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-primary-50 to-accent-50">
      {/* Header */}
      <div className="bg-white shadow-sm sticky top-0 z-40">
        <div className="max-w-6xl mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <button
              onClick={() => navigate(-1)}
              className="flex items-center text-gray-600 hover:text-primary-600 transition-colors"
            >
              <ArrowLeft className="w-5 h-5 mr-2" />
              返回
            </button>
            <h1 className="text-lg font-semibold text-gray-800">绘本详情</h1>
            <button
              onClick={handleToggleFavorite}
              className={`p-2 rounded-full transition-colors ${
                isFavorite 
                  ? 'text-red-500 bg-red-50 hover:bg-red-100' 
                  : 'text-gray-400 hover:text-red-500 hover:bg-red-50'
              }`}
            >
              <Heart className={`w-5 h-5 ${isFavorite ? 'fill-current' : ''}`} />
            </button>
          </div>
        </div>
      </div>

      <div className="max-w-6xl mx-auto px-4 py-6">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Book Preview */}
          <div className="space-y-6">
            {/* Main Image */}
            <div className="relative bg-white rounded-2xl shadow-lg overflow-hidden">
              <div className="aspect-[4/3] relative">
                <img
                  src={book.previewImages?.[currentPage] || book.coverImage}
                  alt={book.title}
                  className="w-full h-full object-cover"
                />
                
                {/* Page Navigation */}
                {totalPages > 1 && (
                  <>
                    <button
                      onClick={handlePrevPage}
                      disabled={currentPage === 0}
                      className="absolute left-2 top-1/2 transform -translate-y-1/2 p-2 bg-white/80 rounded-full shadow-md hover:bg-white transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <ChevronLeft className="w-4 h-4" />
                    </button>
                    <button
                      onClick={handleNextPage}
                      disabled={currentPage === totalPages - 1}
                      className="absolute right-2 top-1/2 transform -translate-y-1/2 p-2 bg-white/80 rounded-full shadow-md hover:bg-white transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <ChevronRight className="w-4 h-4" />
                    </button>
                  </>
                )}
                
                {/* Page Indicator */}
                <div className="absolute bottom-2 left-1/2 transform -translate-x-1/2 flex space-x-1">
                  {Array.from({ length: totalPages }).map((_, index) => (
                    <div
                      key={index}
                      className={`w-2 h-2 rounded-full transition-all ${
                        index === currentPage ? 'bg-white' : 'bg-white/50'
                      }`}
                    />
                  ))}
                </div>
              </div>
            </div>

            {/* Preview Pages */}
            {book.previewImages && book.previewImages.length > 1 && (
              <div className="grid grid-cols-4 gap-2">
                {book.previewImages.slice(0, 4).map((image, index) => (
                  <button
                    key={index}
                    onClick={() => setCurrentPage(index)}
                    className={`aspect-[4/3] rounded-lg overflow-hidden border-2 transition-all ${
                      index === currentPage 
                        ? 'border-primary-500 shadow-md' 
                        : 'border-gray-200 hover:border-primary-300'
                    }`}
                  >
                    <img
                      src={image}
                      alt={`第${index + 1}页`}
                      className="w-full h-full object-cover"
                    />
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Book Info */}
          <div className="space-y-6">
            {/* Basic Info */}
            <div className="bg-white rounded-2xl p-6 shadow-lg">
              <div className="flex items-start justify-between mb-4">
                <div className="flex-1">
                  <h1 className="text-2xl font-bold text-gray-800 mb-2">{book.title}</h1>
                  <p className="text-gray-600 mb-4">{book.description}</p>
                  
                  <div className="flex items-center space-x-4 text-sm text-gray-500 mb-4">
                    <div className="flex items-center">
                      <Star className="w-4 h-4 text-yellow-400 fill-current mr-1" />
                      <span>{book.rating}</span>
                    </div>
                    <div className="flex items-center">
                      <Users className="w-4 h-4 mr-1" />
                      <span>{book.readCount} 人阅读</span>
                    </div>
                    <div className="flex items-center">
                      <Clock className="w-4 h-4 mr-1" />
                      <span>{book.pages} 页</span>
                    </div>
                  </div>

                  <div className="flex flex-wrap gap-2 mb-4">
                    {book.tags.map((tag, index) => (
                      <span
                        key={index}
                        className="px-3 py-1 bg-accent-100 text-accent-700 rounded-full text-sm"
                      >
                        {tag}
                      </span>
                    ))}
                  </div>
                </div>
              </div>

              {/* Price and Purchase */}
              <div className="border-t pt-4">
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center space-x-2">
                    <span className="text-3xl font-bold text-primary-600">¥{book.price}</span>
                    {book.originalPrice && book.originalPrice > book.price && (
                      <span className="text-lg text-gray-400 line-through">¥{book.originalPrice}</span>
                    )}
                  </div>
                  
                  {book.stock && book.stock < 10 && (
                    <span className="text-sm text-orange-600 bg-orange-100 px-2 py-1 rounded">
                      仅剩 {book.stock} 本
                    </span>
                  )}
                </div>

                {/* Quantity Selector */}
                <div className="flex items-center space-x-4 mb-4">
                  <span className="text-gray-700">数量:</span>
                  <div className="flex items-center border rounded-lg">
                    <button
                      onClick={() => setQuantity(Math.max(1, quantity - 1))}
                      className="px-3 py-1 hover:bg-gray-100 transition-colors"
                    >
                      -
                    </button>
                    <span className="px-4 py-1 border-x">{quantity}</span>
                    <button
                      onClick={() => setQuantity(quantity + 1)}
                      className="px-3 py-1 hover:bg-gray-100 transition-colors"
                    >
                      +
                    </button>
                  </div>
                </div>

                {/* Action Buttons */}
                <div className="space-y-3">
                  <button
                    onClick={handleAddToCart}
                    className="w-full flex items-center justify-center px-6 py-3 bg-secondary-500 text-white rounded-xl hover:bg-secondary-600 transition-colors font-medium"
                  >
                    <ShoppingCart className="w-5 h-5 mr-2" />
                    加入购物车
                  </button>
                  
                  <button
                    onClick={handleStartReading}
                    className="w-full flex items-center justify-center px-6 py-3 bg-primary-500 text-white rounded-xl hover:bg-primary-600 transition-colors font-medium"
                  >
                    <BookOpen className="w-5 h-5 mr-2" />
                    开始阅读
                  </button>
                </div>
              </div>
            </div>

            {/* Book Details */}
            <div className="bg-white rounded-2xl p-6 shadow-lg">
              <h3 className="text-lg font-semibold text-gray-800 mb-4">图书详情</h3>
              <div className="space-y-3 text-sm">
                <div className="flex justify-between">
                  <span className="text-gray-500">作者:</span>
                  <span className="text-gray-800">{book.author}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">出版社:</span>
                  <span className="text-gray-800">{book.publisher}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">适读年龄:</span>
                  <span className="text-gray-800">{book.ageRange}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">页数:</span>
                  <span className="text-gray-800">{book.pages} 页</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-500">语言:</span>
                  <span className="text-gray-800">中文</span>
                </div>
              </div>
            </div>

            {/* Reviews */}
            <div className="bg-white rounded-2xl p-6 shadow-lg">
              <h3 className="text-lg font-semibold text-gray-800 mb-4">用户评价</h3>
              <div className="space-y-4">
                {book.reviews && book.reviews.length > 0 ? (
                  book.reviews.map((review, index) => (
                    <div key={index} className="border-b border-gray-100 pb-4 last:border-b-0">
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center space-x-2">
                          <div className="w-8 h-8 bg-primary-100 rounded-full flex items-center justify-center">
                            <span className="text-primary-600 text-sm font-medium">
                              {review.userName.charAt(0)}
                            </span>
                          </div>
                          <span className="text-sm font-medium text-gray-700">{review.userName}</span>
                        </div>
                        <div className="flex items-center">
                          {Array.from({ length: review.rating }).map((_, i) => (
                            <Star key={i} className="w-4 h-4 text-yellow-400 fill-current" />
                          ))}
                        </div>
                      </div>
                      <p className="text-sm text-gray-600">{review.comment}</p>
                      <p className="text-xs text-gray-400 mt-1">{review.date}</p>
                    </div>
                  ))
                ) : (
                  <p className="text-gray-500 text-center py-4">暂无评价</p>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default BookDetailPage;